import React, { useState } from 'react';
import { 
  Layout, 
  Users, 
  FileText, 
  BarChart3, 
  Settings, 
  Shield, 
  Bell, 
  Search,
  CheckCircle,
  Clock,
  AlertCircle,
  ArrowRight,
  Star,
  Calendar,
  Target,
  Activity,
  Layers,
  Zap,
  Globe,
  Database,
  ArrowDown,
  ChevronRight,
  Eye,
  Sparkles
} from 'lucide-react';

const ModuleCenter = ({ setCurrentPage }) => {
  const [viewMode, setViewMode] = useState('architecture'); // architecture | grid | timeline
  const [hoveredModule, setHoveredModule] = useState(null);

  // 模块状态定义
  const moduleStatuses = {
    completed: { label: '已完成', color: 'bg-green-500', textColor: 'text-green-700', bgColor: 'bg-green-50', borderColor: 'border-green-200', icon: CheckCircle },
    inprogress: { label: '开发中', color: 'bg-blue-500', textColor: 'text-blue-700', bgColor: 'bg-blue-50', borderColor: 'border-blue-200', icon: Clock },
    planned: { label: '计划中', color: 'bg-amber-500', textColor: 'text-amber-700', bgColor: 'bg-amber-50', borderColor: 'border-amber-200', icon: Calendar },
    pending: { label: '待规划', color: 'bg-gray-400', textColor: 'text-gray-600', bgColor: 'bg-gray-50', borderColor: 'border-gray-200', icon: AlertCircle }
  };

  // 按架构层次组织的模块定义
  const architectureLayers = [
    {
      id: 'integration',
      title: '整合展示层',
      subtitle: 'Integration & Presentation Layer',
      description: '统一的用户体验和跨模块协作',
      color: 'from-purple-600 to-indigo-600',
      bgPattern: 'bg-gradient-to-br from-purple-50 to-indigo-50',
      modules: [
        {
          id: 'integrated-platform',
          name: 'ESG平台整合原型',
          description: '多产品经理协作的完整ESG平台统一原型展示',
          icon: Globe,
          status: 'completed',
          priority: 'critical',
          version: 'v1.0',
          features: ['统一导航系统', '跨模块数据共享', '业务流程整合', '统一用户体验', '模块协作管理'],
          progress: 100,
          onClick: () => setCurrentPage('integrated-platform')
        }
      ]
    },
    {
      id: 'business',
      title: '核心业务层',
      subtitle: 'Core Business Layer',
      description: '核心ESG业务功能模块',
      color: 'from-emerald-600 to-teal-600',
      bgPattern: 'bg-gradient-to-br from-emerald-50 to-teal-50',
      modules: [
        {
          id: 'workbench',
          name: '工作台系统',
          description: '数据录入、审批流程、报告生成的核心工作台',
          icon: Layout,
          status: 'completed',
          priority: 'high',
          version: 'v1.0',
          features: ['数据录入', '审批流程', '报告生成', '仪表板'],
          progress: 100,
          onClick: () => setCurrentPage('workbench')
        },
        {
          id: 'carbon-footprint',
          name: '碳足迹管理',
          description: '数据收集、碳足迹计算、减排目标、供应链管理',
          icon: Activity,
          status: 'completed',
          priority: 'high',
          version: 'v1.0',
          features: ['数据收集管理', '碳足迹计算', '减排目标跟踪', '供应链管理', '报告披露'],
          progress: 100,
          onClick: () => setCurrentPage('carbon-footprint')
        },
        {
          id: 'carbon-inventory',
          name: '组织碳盘查',
          description: 'AI驱动的组织碳盘查系统，支持单一企业和集团公司',
          icon: Database,
          status: 'completed',
          priority: 'critical',
          version: 'v1.0',
          features: ['AI智能引导', '组织边界管理', '排放源识别', '数据收集', '排放计算', '报告生成'],
          progress: 100,
          onClick: () => setCurrentPage('carbon-inventory')
        }
      ]
    },
    {
      id: 'management',
      title: '管理支撑层',
      subtitle: 'Management Support Layer',
      description: '权限管理、合规监控和分析报告',
      color: 'from-blue-600 to-cyan-600',
      bgPattern: 'bg-gradient-to-br from-blue-50 to-cyan-50',
      modules: [
        {
          id: 'user-management',
          name: '用户管理',
          description: '用户权限、角色管理、组织架构管理',
          icon: Users,
          status: 'inprogress',
          priority: 'high',
          version: 'v1.1',
          features: ['用户注册', '权限管理', '角色分配', '组织架构'],
          progress: 65,
          onClick: () => alert('用户管理模块开发中...')
        },
        {
          id: 'compliance',
          name: '合规管理',
          description: '法规遵循、标准管理、审计支持',
          icon: Shield,
          status: 'planned',
          priority: 'high',
          version: 'v1.3',
          features: ['法规库', '合规检查', '审计报告', '风险评估'],
          progress: 10,
          onClick: () => alert('合规管理规划中...')
        },
        {
          id: 'reporting',
          name: '报告中心',
          description: '高级报告分析、数据可视化、合规报告',
          icon: BarChart3,
          status: 'planned',
          priority: 'medium',
          version: 'v1.2',
          features: ['可视化图表', '自定义报告', '数据分析', '趋势预测'],
          progress: 25,
          onClick: () => alert('报告中心规划中...')
        }
      ]
    },
    {
      id: 'infrastructure',
      title: '基础设施层',
      subtitle: 'Infrastructure Layer',
      description: '系统基础功能和数据服务',
      color: 'from-slate-600 to-gray-600',
      bgPattern: 'bg-gradient-to-br from-slate-50 to-gray-50',
      modules: [
        {
          id: 'data-integration',
          name: '数据集成',
          description: '第三方数据源接入、API管理、数据同步',
          icon: Database,
          status: 'pending',
          priority: 'medium',
          version: 'v1.5',
          features: ['API接口', '数据同步', '第三方集成', '数据验证'],
          progress: 0,
          onClick: () => alert('数据集成待规划...')
        },
        {
          id: 'notifications',
          name: '通知中心',
          description: '消息推送、提醒管理、邮件通知',
          icon: Bell,
          status: 'pending',
          priority: 'low',
          version: 'v1.4',
          features: ['实时通知', '邮件提醒', '消息中心', '订阅管理'],
          progress: 0,
          onClick: () => alert('通知中心待规划...')
        },
        {
          id: 'system-config',
          name: '系统配置',
          description: '系统设置、参数配置、主题定制',
          icon: Settings,
          status: 'pending',
          priority: 'low',
          version: 'v1.6',
          features: ['系统配置', '主题设置', '参数管理', '备份恢复'],
          progress: 0,
          onClick: () => alert('系统配置待规划...')
        }
      ]
    }
  ];

  // 获取所有模块的扁平列表
  const getAllModules = () => {
    return architectureLayers.flatMap(layer => 
      layer.modules.map(module => ({ ...module, layerId: layer.id, layerTitle: layer.title }))
    );
  };

  // 获取状态统计
  const getStatusStats = () => {
    const allModules = getAllModules();
    const stats = {};
    Object.keys(moduleStatuses).forEach(status => {
      stats[status] = allModules.filter(m => m.status === status).length;
    });
    return stats;
  };

  const statusStats = getStatusStats();

  // 优先级颜色映射
  const getPriorityStyle = (priority) => {
    switch (priority) {
      case 'critical': return 'border-red-300 bg-red-50 text-red-700';
      case 'high': return 'border-orange-300 bg-orange-50 text-orange-700';
      case 'medium': return 'border-yellow-300 bg-yellow-50 text-yellow-700';
      case 'low': return 'border-green-300 bg-green-50 text-green-700';
      default: return 'border-gray-300 bg-gray-50 text-gray-700';
    }
  };

  // 架构视图组件
  const ArchitectureView = () => (
    <div className="space-y-6">
      {architectureLayers.map((layer, layerIndex) => (
        <div key={layer.id} className="relative">
          {/* 层次标题 */}
          <div className={`${layer.bgPattern} rounded-xl p-4 mb-4 border border-gray-200`}>
            <div className={`inline-flex items-center px-3 py-1.5 rounded-full bg-gradient-to-r ${layer.color} text-white text-sm font-medium mb-2`}>
              <Layers className="w-4 h-4 mr-2" />
              {layer.title}
            </div>
            <h3 className="text-lg font-bold text-gray-900 mb-1">{layer.subtitle}</h3>
            <p className="text-sm text-gray-600">{layer.description}</p>
          </div>

          {/* 模块卡片 */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 mb-6">
            {layer.modules.map((module) => {
              const Icon = module.icon;
              const statusInfo = moduleStatuses[module.status];
              const StatusIcon = statusInfo.icon;
              const isHovered = hoveredModule === module.id;
              
                              return (
                  <div
                    key={module.id}
                    className={`relative bg-white rounded-lg shadow-md hover:shadow-lg transition-all duration-300 cursor-pointer transform hover:-translate-y-1 border-l-4 ${statusInfo.color} ${isHovered ? 'scale-102 z-10' : ''}`}
                    onClick={module.onClick}
                    onMouseEnter={() => setHoveredModule(module.id)}
                    onMouseLeave={() => setHoveredModule(null)}
                  >
                    {/* 状态指示器 */}
                    <div className={`absolute -top-1.5 -right-1.5 ${statusInfo.color} rounded-full p-1.5 shadow-md`}>
                      <StatusIcon className="w-3 h-3 text-white" />
                    </div>

                    {/* 优先级标签 */}
                    <div className={`absolute top-3 right-3 px-1.5 py-0.5 rounded text-xs font-medium ${getPriorityStyle(module.priority)}`}>
                      {module.priority === 'critical' && '关键'}
                      {module.priority === 'high' && '高'}
                      {module.priority === 'medium' && '中'}
                      {module.priority === 'low' && '低'}
                    </div>

                    <div className="p-4">
                                          <div className="flex items-center space-x-2 mb-3">
                        <div className={`p-2 rounded-lg bg-gradient-to-br ${layer.color} shadow-md`}>
                          <Icon className="w-5 h-5 text-white" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <h4 className="text-base font-bold text-gray-900 truncate">{module.name}</h4>
                          <p className="text-xs text-gray-500">{module.version}</p>
                        </div>
                      </div>
                      
                      <p className="text-xs text-gray-600 mb-3 line-clamp-2 leading-tight">{module.description}</p>
                      
                      {/* 进度条 */}
                      <div className="mb-3">
                        <div className="flex justify-between items-center mb-1">
                          <span className="text-xs text-gray-500">进度</span>
                          <span className="text-xs font-medium text-gray-700">{module.progress}%</span>
                        </div>
                        <div className="w-full bg-gray-200 rounded-full h-1.5">
                          <div 
                            className={`h-1.5 rounded-full transition-all duration-500 ${statusInfo.color}`}
                            style={{ width: `${module.progress}%` }}
                          />
                        </div>
                      </div>

                      {/* 功能特性 */}
                      <div className="space-y-1">
                        <span className="text-xs text-gray-500 font-medium">核心功能</span>
                        <div className="flex flex-wrap gap-1">
                          {module.features.slice(0, 4).map((feature, index) => (
                            <span key={index} className={`px-1.5 py-0.5 text-xs rounded ${statusInfo.bgColor} ${statusInfo.textColor} border ${statusInfo.borderColor}`}>
                              {feature}
                            </span>
                          ))}
                          {module.features.length > 4 && (
                            <span className="px-1.5 py-0.5 text-xs rounded bg-gray-100 text-gray-600 border border-gray-200">
                              +{module.features.length - 4}
                            </span>
                          )}
                        </div>
                      </div>

                                          {/* 悬停时显示的额外信息 */}
                      {isHovered && (
                        <div className="absolute inset-0 bg-white bg-opacity-95 rounded-lg p-4 flex flex-col justify-center items-center backdrop-blur-sm">
                          <Eye className="w-6 h-6 text-blue-500 mb-1" />
                          <p className="text-xs font-medium text-gray-900 mb-1">点击查看详情</p>
                          <p className="text-xs text-gray-600 text-center">
                            {statusInfo.label} · {module.features.length} 个功能
                          </p>
                        </div>
                      )}
                  </div>
                </div>
              );
            })}
          </div>

          {/* 层级连接线 */}
          {layerIndex < architectureLayers.length - 1 && (
            <div className="flex justify-center mb-2">
              <div className="flex flex-col items-center">
                <ArrowDown className="w-5 h-5 text-gray-400 animate-bounce" />
                <div className="w-px h-4 bg-gradient-to-b from-gray-300 to-transparent" />
              </div>
            </div>
          )}
        </div>
      ))}
    </div>
  );

  // 传统网格视图
  const GridView = () => {
    const allModules = getAllModules();
    
    return (
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {allModules.map((module) => {
          const Icon = module.icon;
          const statusInfo = moduleStatuses[module.status];
          const StatusIcon = statusInfo.icon;
          
          return (
            <div
              key={module.id}
              className="bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow duration-200 cursor-pointer"
              onClick={module.onClick}
            >
              <div className="p-6">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-center space-x-3">
                    <div className="p-2 bg-blue-100 rounded-lg">
                      <Icon className="w-6 h-6 text-blue-600" />
                    </div>
                    <div>
                      <h3 className="text-lg font-semibold text-gray-900">{module.name}</h3>
                      <p className="text-sm text-gray-500">{module.version}</p>
                    </div>
                  </div>
                  <div className={`flex items-center space-x-1 px-2 py-1 rounded-full text-xs font-medium border ${statusInfo.textColor} ${statusInfo.bgColor} ${statusInfo.borderColor}`}>
                    <StatusIcon className="w-3 h-3" />
                    <span>{statusInfo.label}</span>
                  </div>
                </div>
                
                <p className="text-sm text-gray-600 mb-4">{module.description}</p>
                
                <div className="space-y-3">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-500">所属层级</span>
                    <span className="font-medium">{module.layerTitle}</span>
                  </div>
                  
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-500">完成进度</span>
                    <span className="font-medium">{module.progress}%</span>
                  </div>
                  
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div 
                      className={`h-2 rounded-full ${statusInfo.color}`}
                      style={{ width: `${module.progress}%` }}
                    />
                  </div>
                  
                  <div className="flex items-center justify-between">
                    <div className="flex flex-wrap gap-1">
                      {module.features.slice(0, 2).map((feature, index) => (
                        <span key={index} className={`px-2 py-1 text-xs rounded ${statusInfo.bgColor} ${statusInfo.textColor}`}>
                          {feature}
                        </span>
                      ))}
                    </div>
                    <ChevronRight className="w-4 h-4 text-gray-400" />
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 via-blue-50 to-indigo-50">
      {/* 头部 */}
      <div className="bg-white shadow-lg border-b border-gray-200">
        <div className="max-w-7xl mx-auto px-4 py-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <div className="p-2.5 bg-gradient-to-br from-blue-600 to-purple-600 rounded-xl shadow-lg">
                <Target className="w-7 h-7 text-white" />
              </div>
              <div>
                <h1 className="text-2xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
                  ESG功能中心
                </h1>
                <p className="text-gray-600 text-sm">分层架构 · 统一管理 · 协作开发</p>
              </div>
              <div className="hidden md:flex items-center space-x-2">
                <Sparkles className="w-5 h-5 text-yellow-500" />
                <span className="text-sm font-medium text-gray-600">智能化平台管理</span>
              </div>
            </div>
            
            <div className="flex items-center space-x-4">
              <div className="flex items-center space-x-2">
                <span className="text-sm text-gray-500 font-medium">视图模式:</span>
                <select 
                  value={viewMode} 
                  onChange={(e) => setViewMode(e.target.value)}
                  className="px-4 py-2 border border-gray-300 rounded-lg text-sm bg-white shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                >
                  <option value="architecture">架构视图</option>
                  <option value="grid">网格视图</option>
                </select>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 统计概览 */}
      <div className="max-w-7xl mx-auto px-4 py-6">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
          {Object.entries(statusStats).map(([status, count]) => {
            const statusInfo = moduleStatuses[status];
            const StatusIcon = statusInfo.icon;
            
                          return (
                <div key={status} className="bg-white rounded-lg shadow-md p-4 border border-gray-100 hover:shadow-lg transition-shadow duration-200">
                  <div className="flex items-center space-x-3">
                    <div className={`p-2.5 rounded-lg ${statusInfo.color} shadow-md`}>
                      <StatusIcon className="w-5 h-5 text-white" />
                    </div>
                    <div>
                      <p className="text-sm font-medium text-gray-600">{statusInfo.label}</p>
                      <p className="text-2xl font-bold text-gray-900">{count}</p>
                    </div>
                  </div>
                </div>
            );
          })}
        </div>

        {/* 内容区域 */}
        {viewMode === 'architecture' ? <ArchitectureView /> : <GridView />}
      </div>
    </div>
  );
};

export default ModuleCenter; 